package com.hngc.controller;


import com.hngc.entity.User;
import com.hngc.services.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.List;

/**
 * RestController的作用
 * 1.如果返回的是字符串，那就返回字符串
 * 2. 如果返回的是对象或者集合，就解析成json格式
 * 3. 如果需要跳转页面的话，返回值只能是ModelAndView
 */
@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/getUserById")
    public ModelAndView getUserById() {
        User user = userService.getUserById(2);
        ModelAndView mv = new ModelAndView();
        mv.addObject("user", user);
        mv.setViewName("user");
        return mv;
    }

    @RequestMapping("/getAllUsers")
    public ModelAndView getAllUsers() {
        ModelAndView mv = new ModelAndView();
        List<User> list = userService.getAllUsers();
        mv.addObject("list", list);
        mv.setViewName("userlist");
        return mv;
    }


    @RequestMapping("/addUser")
    public ModelAndView addUser(User user) {
        userService.addUser(user);
        return new ModelAndView("redirect:/getAllUsers.do");
    }


    //_______________________________________________________________

    @RequestMapping("/user")
    public User user() {
        User u = new User(1, "zhangsan", 22, "2023");
        return u;
    }

    @RequestMapping("/hello")
    public String hello() {
        return "hello";
    }

    @RequestMapping("/userList")
    public List<User> userList() {
        User u = new User(1, "zhangsan", 22, "2023");
        User u2 = new User(2, "lisi", 23, "2023");
        User u3 = new User(3, "wangwu", 33, "2024");
        List<User> list = new ArrayList<>();
        list.add(u);
        list.add(u2);
        list.add(u3);

        return list;

    }


}
